package com.chinawlx.wlxteacher.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.bean.WLXCommentListBean;
import com.chinawlx.wlxteacher.ui.activity.WLXParentRplyctivity;
import com.chinawlx.wlxteacher.ui.activity.WLXPhotoViewActivity;
import com.chinawlx.wlxteacher.ui.activity.WLXPlayVideoActivity;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.record.MediaManager;
import com.chinawlx.wlxteacher.wlx_homework;
import com.chinawlx.wlxteacher.wlx_homework_comment;
import com.chinawlx.wlxteacher.wlx_homework_commentDao;
import com.chinawlx.wlxteacher.wlx_student;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 作者:黄帅
 * 时间:16/8/29
 * 描述: 回复列表界面适配器
 */
public class WLXCommentListAdapter extends BaseAdapter {

    private Context mContext;
    private List<wlx_homework> mHomeworks = new ArrayList<>();
    private int currentPosition = -1;

    public WLXCommentListAdapter(Context context) {
        this.mContext = context;
    }

    public void setData(List<wlx_homework> wlx_homeworks) {
        this.mHomeworks.clear();
        this.mHomeworks.addAll(wlx_homeworks);
    }

    public void addData(List<wlx_homework> wlx_homeworks) {
        this.mHomeworks.addAll(wlx_homeworks);
    }

    @Override
    public int getCount() {
        return mHomeworks.size();
    }

    @Override
    public Object getItem(int position) {
        return mHomeworks.get(position);
    }

    @Override
    public long getItemId(int position) {
        return mHomeworks.get(position).getStudent_id();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_commentlist_view,
                    null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //initData
        initData(holder, position);
        return convertView;
    }

    //初始化数据
    private void initData(final ViewHolder holder, final int position) {
        wlx_homework wlx_homework = mHomeworks.get(position);
        //数据处理
        //通过student_id查找student表,拿到名称和头像的URL
        final wlx_student student = WLXGreenDaoUtil.getStudentDao().load(wlx_homework
                .getStudent_id() + "");
        if (student != null) {
            holder.mTvUserName.setText(student.getRealname());
            Glide.with(mContext).load(student.getAvatar_url()).placeholder(R.drawable.place_holder)
                    .into
                            (holder.mUserPhoto);
        } else {
            holder.mTvUserName.setText(wlx_homework.getStudent_id() + "");
        }
        holder.mTvContent.setText(wlx_homework.getContent());

        //获取时间
        final long current_time = System.currentTimeMillis() / 1000L;
        long creatData = wlx_homework.getCreation_date();
        //获取现在时间和创始时间的差值
        final String time = WLXDateUtil.getDistanceTime(creatData, current_time);
        holder.mTvTime.setText(time);

        String extend_info = wlx_homework.getExtend_info();
        final WLXCommentListBean.DataBean.HomeworkListBean.ExtendBean extendBean = new Gson()
                .fromJson
                        (extend_info, WLXCommentListBean.DataBean.HomeworkListBean.ExtendBean
                                .class);

        if (extendBean.getResource_url().size() > 0) {
            final String code = wlx_homework.getHomework_content_code();
            String picUrl = "";
            switch (code) {
                case "image"://图片
                    picUrl = extendBean.getResource_url().get(0);
                    holder.mIvIsVideo.setVisibility(View.GONE);
                    break;
                case "video"://视频
                    String ss = extendBean.getResource_url().get(0);
                    picUrl = ss.substring(0, ss.length() - 3) + "png";
                    holder.mIvIsVideo.setVisibility(View.VISIBLE);
                    break;
            }
            Glide.with(mContext).load(picUrl).placeholder(R.drawable.place_holder)
                    .into
                            (holder.mIvLeft);
            holder.mIvLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = null;
                    List<String> resource_url = extendBean.getResource_url();

                    switch (code) {
                        case "image"://图片
                            ArrayList<String> urls = new ArrayList<>();
                            urls.addAll(resource_url);
                            intent = new Intent(mContext,
                                    WLXPhotoViewActivity.class);
                            intent.putExtra(WLXPhotoViewActivity.URLS, urls);
                            break;
                        case "video"://视频
                            try {
                                String videoUrl = extendBean
                                        .getResource_url().get(0);
                                intent = new Intent(mContext,
                                        WLXPlayVideoActivity.class);
                                intent.putExtra(WLXPlayVideoActivity.VIDEO_URL, videoUrl);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                    }
                    mContext.startActivity(intent);
                }
            });
        }

        holder.mTvCommentReplay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, WLXParentRplyctivity.class);
                intent.putExtra("homework_id", mHomeworks.get(position)
                        .getHomework_id());
                intent.putExtra("student_id", mHomeworks.get(position).getStudent_id()
                        + "");
                intent.putExtra("homework_content_code", mHomeworks.get(position)
                        .getHomework_content_code());
                intent.putExtra("time", time);
                intent.putExtra("extend_info", mHomeworks.get(position)
                        .getExtend_info());
                intent.putExtra("content", mHomeworks.get(position).getContent());
                intent.putExtra("userIcon", student == null ? "" : student.getAvatar_url());
                mContext.startActivity(intent);
            }
        });

        //排序,找到最后一条
        List<wlx_homework_comment> list = WLXGreenDaoUtil.getHomeWorCommentkDao().queryBuilder()
                .where(wlx_homework_commentDao
                        .Properties.Homework_id.eq(wlx_homework.getHomework_id())).orderDesc
                        (wlx_homework_commentDao.Properties.Creation_date).list();
        for (wlx_homework_comment c : list) {
            WLXLogUtil.d("创建时间:" + c.getCreation_date());
        }

        if (list.size() > 0) {
            wlx_homework_comment wlx_homework_comment = list.get(0);
            switch (wlx_homework_comment.getComment_content_code()) {
                case "audio"://音频
                    if (currentPosition == position) {
                        holder.mTvVoice.setBackgroundResource(R.drawable.voiceplaying);
                    } else {
                        holder.mTvVoice.setBackgroundResource(R.drawable.voiceplayback);
                    }
                    holder.mTvText.setVisibility(View.GONE);
                    holder.mTvVoice.setVisibility(View.VISIBLE);
                    String extend_info_comment = wlx_homework_comment.getExtend_info();

                    final WLXCommentListBean.DataBean.HomeworkListBean.ExtendBean
                            extendBeanComment = new Gson().fromJson
                            (extend_info_comment, WLXCommentListBean.DataBean.HomeworkListBean
                                    .ExtendBean
                                    .class);
                    holder.mTvVoice.setText(extendBeanComment.getDuration() + "''");
                    holder.mTvVoice.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (currentPosition == position) {
                                currentPosition = -1;
                                holder.mTvVoice.setBackgroundResource(R.drawable.voiceplayback);
                                return;
                            }
                            String path = extendBeanComment.getResource_url().get(0);
                            if (path.endsWith(".caf")) {
                                WLXCustomToast.show("caf格式无法播放");
                                currentPosition = -1;
                                holder.mTvVoice.setBackgroundResource(R.drawable.voiceplayback);
                                return;
                            }
                            currentPosition = position;
                            notifyDataSetChanged();

                            MediaManager.playSound(extendBeanComment.getResource_url().get(0), new
                                    MediaPlayer.OnCompletionListener() {
                                        @Override
                                        public void onCompletion(MediaPlayer mp) {
                                            //播放完成,UI改回来
                                            currentPosition = position;
                                            holder.mTvVoice.setBackgroundResource(R.drawable
                                                    .voiceplayback);
                                        }
                                    });
                        }
                    });
                    break;
                case "text"://文字
                    holder.mTvText.setVisibility(View.VISIBLE);
                    holder.mTvVoice.setVisibility(View.GONE);
                    holder.mTvText.setText(wlx_homework_comment.getContent());
                    break;

            }
        }
    }

    static class ViewHolder {
        @BindView(R.id.user_photo)
        CircleImageView mUserPhoto;
        @BindView(R.id.tv_user_name)
        TextView mTvUserName;
        @BindView(R.id.tv_time)
        TextView mTvTime;
        @BindView(R.id.tv_comment_replay)
        TextView mTvCommentReplay;
        @BindView(R.id.tv_voice)
        TextView mTvVoice;
        @BindView(R.id.tv_text)
        TextView mTvText;
        @BindView(R.id.iv_left)
        ImageView mIvLeft;
        @BindView(R.id.iv_is_video)
        ImageView mIvIsVideo;
        @BindView(R.id.tv_content)
        TextView mTvContent;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
